// 合同录入弹窗
<template>
  <div class="addDialog basic-from" :class="{previewPage: type == 'preview'}">
    <el-dialog
      custom-class="small-padding-dialog"
      :close-on-click-modal="false"
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="1200px"
      @close="handleClosed"
    >
      <el-form ref="form" :rules="rules" :model="operationContract" class="form-wrap">
        <el-form-item label="工程名称" class="listFormItem" prop="engineeringName">
          <el-button class="add" type="primary" size="mini" @click="$refs.propertyChoose.show();" v-if="type === 'add'">选择</el-button>
          <el-input v-halfCharCode v-model="operationContract.engineeringName" placeholder="请选择工程名称" readonly />
        </el-form-item>
        <el-form-item label="单位名称" prop="unitName">
          <el-input v-halfCharCode v-model="operationContract.unitName" readonly placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="物业名称" prop="propertyName">
          <el-input v-halfCharCode v-model="operationContract.propertyName" readonly placeholder="请输入物业名称" />
        </el-form-item>
        <el-form-item label="合同名称" class="breakItem" prop="contractName">
          <el-input v-halfCharCode v-model.trim="operationContract.contractName" :disabled="isReadonly" maxlength="20" placeholder="请输入合同名称" />
        </el-form-item>
        <el-form-item label="合同编号" prop="contractNumber">
          <el-input v-halfCharCode v-model.trim="operationContract.contractNumber" disabled maxlength="30" placeholder="请输入合同编号" />
        </el-form-item>
        <el-form-item label="签订日期" prop="signTime">
          <el-date-picker
            v-model="operationContract.signTime"
            format="yyyy-MM-dd"
            type="datetime"
            placeholder="请输入签订日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :disabled="isReadonly"
          />
        </el-form-item>

        <el-form-item label="合同金额" prop="totalAmount">
          <el-input
            v-halfCharCode
            v-model="operationContract.totalAmount"
            oninput="value=value.replace(/[^0-9.]/g,'')"
            maxlength="15"
            placeholder="请输入合同金额"
            v-if="!isReadonly"
          />
          <el-input :value="operationContract.totalAmount | thousandMoney" disabled v-else />
        </el-form-item>
        <el-form-item label="工期" prop="constructionPeriod">
          <el-input v-halfCharCode v-model.number="operationContract.constructionPeriod" maxlength="5" :disabled="isReadonly" placeholder="请输入工期">
            <i slot="suffix">日历日</i>
          </el-input>
        </el-form-item>
        <el-form-item label="保修期" prop="warrantyPeriod">
          <el-input
            v-halfCharCode
            v-model.number="operationContract.warrantyPeriod"
            maxlength="3"
            :disabled="isReadonly"
            oninput="value=value.replace(/[^\d]/g,'')"
            placeholder="请输入保修期"
          >
            <i slot="suffix">月</i>
          </el-input>
        </el-form-item>
        <el-form-item label="保证金" prop="margin">
          <el-input v-model="operationContract.margin" v-only-number="{min:0,precision:2}" maxlength="20" placeholder="请输入保证金" v-if="!isReadonly">
            <i slot="suffix">元</i>
          </el-input>
          <el-input :value="operationContract.margin | thousandMoney" disabled v-else />
        </el-form-item>
        <el-form-item label="付款方式" class="full" prop="payMethod">
          <el-input
            v-halfCharCode
            v-model="operationContract.payMethod"
            type="textarea"
            :disabled="type === 'preview'"
            maxlength="64"
            placeholder="请输入付款方式"
          />
        </el-form-item>
        <el-form-item label="备注" class="full" prop="remarks">
          <el-input v-halfCharCode v-model="operationContract.remarks" type="textarea" maxlength="200" :disabled="isReadonly" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="服务价目列表" class="full" prop="operateContractDetailList">
          <el-button size="mini" type="primary" style="float: right" @click="addDetailList" v-if="type !== 'preview'">添加</el-button>
          <el-table :data="operateContractDetailList" class="full">
            <el-table-column type="index" label="序号" width="50" />
            <el-table-column prop="unitPrice" label="单价(元/m²)" width="180">
              <template slot-scope="scope">
                <el-input
                  v-halfCharCode
                  oninput="value=value.replace(/[^0-9.]/g,'')"
                  maxlength="12"
                  v-model="scope.row.unitPrice"
                  placeholder="单价(元/m²)"
                  v-if="!isReadonly"
                />
                <el-input :value="scope.row.unitPrice | thousandMoney" disabled v-else />
              </template>
            </el-table-column>
            <el-table-column prop="costItems" label="费用项目">
              <template slot-scope="scope">
                <el-input v-halfCharCode v-model="scope.row.costItems" maxlength="50" placeholder="项目名称" :disabled="isReadonly" />
              </template>
            </el-table-column>
            <el-table-column prop="paymentAmount" label="付款金额(元)">
              <template slot-scope="scope">
                <el-input
                  v-halfCharCode
                  v-model="scope.row.paymentAmount"
                  oninput="value=value.replace(/[^0-9.]/g,'')"
                  maxlength="15"
                  placeholder="付款金额(元)"
                  v-if="!isReadonly"
                />
                <el-input :value="scope.row.paymentAmount | thousandMoney" disabled v-else />
              </template>
            </el-table-column>
            <el-table-column prop="discountAmount" label="折扣金额(元)">
              <template slot-scope="scope">
                <el-input
                  v-halfCharCode
                  v-model="scope.row.discountAmount"
                  oninput="value=value.replace(/[^0-9.]/g,'')"
                  maxlength="15"
                  placeholder="折扣金额(元)"
                  v-if="!isReadonly"
                />
                <el-input :value="scope.row.discountAmount | thousandMoney" disabled v-else />
              </template>
            </el-table-column>
            <el-table-column prop="finallyAmount" label="最终金额(元)">
              <template slot-scope="scope">
                <span>{{getTotalCount(scope.$index, scope.row.paymentAmount, scope.row.discountAmount)}}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" v-if="type !== 'preview'">
              <template slot-scope="scope">
                <el-button size="mini" type="text" @click="releteDetailList(scope.$index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <!-- 工程选择弹窗 -->
      <propertyChooseDialog ref="propertyChoose" dialogType="contract" @changeProperty="handlePropertyChange" />
      <div slot="footer">
        <el-button @click="$bus.$emit('operationLog',operationContract.obtId)" v-if="type==='preview'">操作日志</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button v-if="type !== 'preview'" type="primary" v-throttle="[save]">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import propertyChooseDialog from "@/views/wy-operate/components/propertyChooseDialog";
import { changeContract, getContractById, checkContractRepeat, maxContractNumber } from "@/views/wy-operate/api/repair.js";
export default {
  name: 'addDepartment',
  inject: ['initList'],
  components: {
    propertyChooseDialog
  },
  data () {
    return {
      type: 'add',//弹窗类型，默认新增
      //弹窗开关
      dialogVisible: false,
      //合同基本信息
      operationContract: {
        contractId: '', //合同id
        supplierId: '',//供应商id
        businessType: '',//业务类型
        engineeringName: '',//工程名称
        roomId: '',//物业id
        propertyName: '',//物业名称
        area: '',//物业面积
        contractType: '',//合同类型
        contractSource: '',//合同来源
        signTime: '',//签订时间
        contractNumber: '',//合同编号
        contractName: '',//合同名称
        unitType: '',//单位类型
        unitName: '',//单位名称
        startTime: '',//开工时间
        endTime: '',//竣工时间
        constructionPeriod: '',//工期
        budgetAmount: '',//预算金额
        censorshipAmount: '',//送审金额
        approvalAmount: '',//审定金额
        contractAmount: '',//合同金额
        totalAmount: '',//总金额
        payMethod: '',//付款方式
        remarks: '',//备注
        billId: '',//工单id
        warrantyPeriod: 0,//保修期-单位月
        margin: '',//保证金
      },
      //服务价目列表
      operateContractDetailList: [],
    }
  },
  computed: {
    // 是否只读
    isReadonly () {
      return this.type === 'preview'
    },
    // 校验规则
    rules () {
      return {
        engineeringName: [{ required: true, message: '工程名称不能为空', trigger: 'blur' }],
        contractName: [
          { required: true, message: '合同名称不能为空', trigger: 'blur' },
          { validator: this.checkContractName, trigger: 'blur' }
        ],
        contractNumber: [
          { required: true, message: '合同编号不能为空', trigger: 'blur' },
          { validator: this.checkContractNumber, trigger: 'blur' }
        ],
        propertyName: [{ required: true, message: '物业名称不能为空', trigger: 'blur' }],
        unitName: [{ required: true, message: '单位名称不能为空', trigger: 'blur' }],
        signTime: [{ required: true, message: '签订日期不能为空', trigger: 'blur' }],
        totalAmount: [
          { required: true, message: '合同金额不能为空', trigger: 'blur' },
          { pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/, message: "请输入正确的金额", trigger: "blur" },
        ],
        constructionPeriod: [
          { required: true, message: '工期不能为空', trigger: 'blur' },
          { type: 'number', min: 0, message: '请输入正确工期（必须为数字且最小为0）', trigger: 'blur' }
        ],
        payMethod: [{ required: true, message: '付款方式不能为空', trigger: 'blur' }],
        margin: [{ required: true, message: "请输入保证金", trigger: "blur" }]
      }
    },
    // 弹窗标题计算
    dialogTitle () {
      return {
        'preview': '查看',
        'edit': '编辑',
        'add': '新增'
      }[this.type]
    },
  },
  methods: {
    //开启弹窗
    async show ({ type, data = {} }) {
      //console.log(data, type, this.operationContract)
      if (['preview', 'edit'].includes(type)) {
        const res = await getContractById(data.contractId)
        const { operationContract, operateContractDetailList } = res.data.data
        //合同基本信息(获取详情没有返回保证金字段，造成了保存不通过的bug，前端手动先加上 2021-4-23 10:17)
        this.operationContract = { margin: '', ...operationContract };
        //服务价目列表
        this.operateContractDetailList = operateContractDetailList;

      } else {
        const res = await maxContractNumber(data.contractId)
        this.operationContract.contractNumber = res.data.msg
      }
      this.type = type;
      this.dialogVisible = true;
    },
    // 提交新增
    save () {
      //this.dialogVisible = false
      if (['edit', 'add'].includes(this.type)) {
        this.$refs.form.validate((valid) => {
          if (valid && this.customValidate()) {
            const params = {
              operationContract: this.operationContract,
              operateContractDetailList: this.operateContractDetailList,
              obtId: this.operationContract.obtId
            }
            changeContract(params, this.type).then(res => {
              if (res.data.code == 0) {
                this.$message.success(`${this.dialogTitle}成功!`);
                this.initList({ current: 1, queryString: '', businessType: '' })
                this.dialogVisible = false;
              } else {
                this.$message.error(res.data.code)
              }
            })
          }
        });
      }

    },
    // 自定义表单验证
    customValidate () {
      if (this.operateContractDetailList.length) {
        if (this.operateContractDetailList.some(item => item.unitPrice == '')) {
          this.$message.error('单价不能为空')
          return false
        } else if (this.operateContractDetailList.some(item => !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(item.unitPrice))) {
          this.$message.error('请输入正确的单价')
          return false
        } else if (this.operateContractDetailList.some(item => item.costItems == '')) {
          this.$message.error('费用项目不能为空')
          return false
        } else if (this.operateContractDetailList.some(item => item.paymentAmount == '')) {
          this.$message.error('付款金额不能为空')
          return false
        } else if (this.operateContractDetailList.some(item => !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(item.paymentAmount))) {
          this.$message.error('请输入正确的付款金额')
          return false
        } else if (this.operateContractDetailList.some(item => !/(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/.test(item.discountAmount))) {
          this.$message.error('请输入正确的折扣金额')
          return false
        }
      }
      return true
    },
    // 添加物业价目明细
    addDetailList () {
      this.operateContractDetailList.push({
        contractDetailId: '',//价目表id
        contractId: '',//合同id  后台已做统一赋值为合同基本信息表id
        unitPrice: '',//单价
        costItems: '',//费用项目
        paymentAmount: '',//付款金额
        discountAmount: '',//折扣金额
        finallyAmount: '',//最终金额
        remarks: '',//备注
      })
    },
    // 删除价目明细
    releteDetailList (index) {
      this.operateContractDetailList.splice(index, 1)
    },
    // 计算价格
    getTotalCount (index, paymentAmount = 0, discountAmount = 0) {
      let totalCount = 0;
      totalCount = (paymentAmount - discountAmount).toFixed(2)
      this.operateContractDetailList[index].finallyAmount = totalCount
      return totalCount
    },
    // 选择预算回调
    handlePropertyChange (data) {
      this.operationContract = {
        ...this.operationContract,
        ...data,
        totalAmount: data.approvalAmount,
        contractName: data.engineeringName + '施工工程'
      }
    },
    //弹窗关闭监听
    handleClosed () {
      this.operationContract = {
        contractId: '',
        supplierId: '',
        businessType: '',
        engineeringName: '',
        roomId: '',
        propertyName: '',
        area: '',
        contractType: '',
        contractSource: '',
        signTime: '',
        contractNumber: '',
        contractName: '',
        unitType: '',
        unitName: '',
        startTime: '',
        endTime: '',
        constructionPeriod: '',
        budgetAmount: '',
        censorshipAmount: '',
        approvalAmount: '',
        contractAmount: '',
        totalAmount: '',
        payMethod: '',
        remarks: '',
        billId: '',
        warrantyPeriod: 0,
        margin: '',
      }
      this.operateContractDetailList = []
      this.$refs.form.resetFields()
    },
    // 合同名称校验
    checkContractName (rule, value, callback) {
      let params = { vType: '1', value, id: this.operationContract.contractId }
      checkContractRepeat(params).then(res => {
        res.data.data == 1 ? callback(new Error("合同名称重复")) : callback()
      })

    },
    // 合同编号
    checkContractNumber (rule, value, callback) {
      let params = { vType: '2', value, id: this.operationContract.contractId }
      checkContractRepeat(params).then(res => {
        res.data.data == 1 ? callback(new Error("合同编号重复")) : callback()
      })
    },
  },
}
</script>

<style lang="scss" scoped>
@import "src/views/wy-operate/css/operate.scss";
</style>
